package link.hwx.controller.u9;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import link.hwx.entity.oa.OaUserInfo;
import link.hwx.service.oa.OaInfoService;
import link.hwx.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cx/srm")
public class SrmShippingDemandOpenApi {
    @Autowired
    private OaInfoService oaInfoMapper;

    @PostMapping("/createShipping")
    public AjaxResult sCreateSd(@RequestBody Map<String, Object> jsonStr) {
        if (jsonStr == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            return AjaxResult.error("数据不能为空!");
        }
        String result = createPr(jsonStr);
        if (StringUtils.isNotEmpty(result)) {
            JSONObject resultmap = JSON.parseObject(result);
            if (resultmap.getBoolean("Success")) {
                String mCode = resultmap.getString("VoucherCode");
                String requestId = jsonStr.get("requestId") + "";
                //修改oa表单标题
                //oaInfoService.updateWorkflowTableTitle(" srm" + mCode, "73098", "6");
                oaInfoMapper.updateSdByRequestId(CommonSetData.oaShippingDemandTableMainDbNameD, " srm" + mCode, requestId);
                return AjaxResult.success();
            } else {
                return AjaxResult.error(resultmap.getString("Message"));
            }
        }
        return AjaxResult.error();
    }
    public String createPr(Map<String, Object> oaMapData) {
        String srmUrl = CommonSetData.serveSrmIp + CommonSetData.srmSdUrlCreat;
        String userpwd = StringUtil.md5(CommonSetData.srmUserPwd);
        JSONObject user = new JSONObject();
        user.put("usercode", CommonSetData.srmUserCode);
        user.put("userpwd", userpwd);
        JSONObject voucher = new JSONObject();
        voucher.put("voucherno", CommonSetData.sDvoucherno);
        voucher.put("formid", CommonSetData.sDformid);
        //组装head头数据
        JSONObject head = new JSONObject();
        head.put("ccode",oaMapData.get("lcbh"));
        head.put("cmaker",oaMapData.get("sqrmc"));
        head.put("cmakercode",oaMapData.get("sqrbh"));
        head.put("cremark",oaMapData.get("bz"));
        head.put("cu8orgcode",oaMapData.get("zth"));
        head.put("curgency","1");
        head.put("cstate","通过");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        head.put("ddate",sdf.format(new Date()));
        head.put("crequireman_id",oaMapData.get("xqrid"));
        head.put("crequireman_code",oaMapData.get("sqrbh"));//需求人编码
        head.put("crequireman_name",oaMapData.get("sqrmc"));//需求人名称
        head.put("cpurtype_id",oaMapData.get("cglx"));
        head.put("csource",oaMapData.get("ly"));
        head.put("corg_id",oaMapData.get("zzid"));
        head.put("cdep_id",oaMapData.get("bmid"));
        head.put("corg_code",oaMapData.get("zzid"));
        head.put("corg_name",oaMapData.get("zzmc"));//组织名称
        head.put("cdep_code",oaMapData.get("bmid"));//部门编码
        head.put("cdep_name",oaMapData.get("bmmc"));//部门名称
        head.put("cpurtype_code","002");//采购类型编码
        head.put("cpurtype_name","物流运输类");//采购类型名称
        head.put("csourcename",oaMapData.get("lymc"));//来源名称


        //组装body数据
        JSONObject armbody = new JSONObject();
        JSONArray focus_srm_requisitionroutec = new JSONArray();
        List<List<Map<String, Object>>> detailList = (List<List<Map<String, Object>>>) oaMapData.get("detailData");
        for (int i = 0; i < detailList.size(); i++) {
            for (int j = 0; j < detailList.get(i).size(); j++) {
                Map<String, Object> detal = detailList.get(i).get(j);//列数据;
                JSONObject srmLine = new JSONObject();
                srmLine.put("cck",detal.get("ck"));
                srmLine.put("cdepartureadd",detal.get("xxzhdz"));
                srmLine.put("cdestinationadd",detal.get("xxxhdz"));
                srmLine.put("cerpc1",detal.get("c1"));
                srmLine.put("cerpc2",detal.get("c2"));
                srmLine.put("cerpc3",detal.get("c3"));
                srmLine.put("cerpc4",detal.get("c4"));
                srmLine.put("cerpc5",detal.get("c5"));
                srmLine.put("cerpc6",detal.get("c6"));
                srmLine.put("cerpc7",detal.get("c7"));
                srmLine.put("cerpc8",detal.get("c8"));
                srmLine.put("cerpcustcode",detal.get("u8khid"));
                srmLine.put("cerpcustname",detal.get("u8khmc"));
                srmLine.put("cerpdepcode",detal.get("u8xsbmid"));
                srmLine.put("cerpdepname",detal.get("u8xsbmmc"));
                srmLine.put("cerpinvcode",detal.get("u8chbm"));
                srmLine.put("cerpinvname",detal.get("u8chmc"));
                srmLine.put("cerpinvstd",detal.get("u8ggxh"));
                srmLine.put("cerpinvunit",detal.get("u8jldw"));
                srmLine.put("cerpinvunitcode",detal.get("u8jldwbm"));
                srmLine.put("cerppersoncode",detal.get("u8ywybm"));
                srmLine.put("cerppersonname",detal.get("u8ywymc"));
                srmLine.put("cerpsaltypecode",detal.get("u8xslxbm"));
                srmLine.put("cerpsaltypename",detal.get("u8xslx"));
                srmLine.put("cerpsccode",detal.get("u8fyfsbm"));
                srmLine.put("cerpscname",detal.get("u8fyfs"));
                srmLine.put("cfhck",detal.get("fhck"));
                srmLine.put("cgxsorderid",detal.get("ddid"));
                srmLine.put("chetongcode",detal.get("hth"));
                srmLine.put("cinvname",detal.get("yshw"));
                srmLine.put("clineremark",detal.get("mxbz"));
                srmLine.put("corderautoid",detal.get("ddmxid"));
                srmLine.put("cordercode",detal.get("ddh"));
                srmLine.put("cordercorpcode",detal.get("zth"));
                srmLine.put("corderid",detal.get("dd"));
                srmLine.put("cordersuppliername",detal.get("khgys"));
                srmLine.put("cspec",detal.get("ggxh"));
                srmLine.put("cuom_name",detal.get("jldw"));
                srmLine.put("dcardate",detal.get("ycsj"));
                srmLine.put("ddeliverydate",detal.get("yqddsj"));
                srmLine.put("idanjia",detal.get("dj"));
                srmLine.put("iinqquan",detal.get("xjsl"));
                srmLine.put("iorderquan",detal.get("ddsl"));
                srmLine.put("iquan",detal.get("sl1"));
                srmLine.put("ishipmentquan",detal.get("fyjhsl"));
                srmLine.put("ishuilv",detal.get("sl"));
                srmLine.put("ivolume",detal.get("tjm3"));
                srmLine.put("iyquan",detal.get("iyquan"));
                srmLine.put("kcautoid",detal.get("kcmxid"));
                srmLine.put("kcid",detal.get("kcid"));
                srmLine.put("kcsl",detal.get("kcsl"));
                srmLine.put("lotnumber",detal.get("ph"));
                srmLine.put("kcdw",detal.get("kcdw"));
                srmLine.put("dcartype",detal.get("yclx"));
                srmLine.put("croute_id",detal.get("yslx"));
                srmLine.put("cordertype",detal.get("u8xslx"));
                srmLine.put("cfhckcode",detal.get("fhckbm"));
                srmLine.put("cfhckid",detal.get("fhckid"));
                srmLine.put("cerpordermaker",detal.get("cMaker"));
                srmLine.put("cerprdcode",detal.get("rklb"));


                //处理附件
//                if (detal.get("scfj")!=null&&detal.get("scfj")!=""){
//                    String sjarry[] = detal.get("scfj").toString().split(",");
//                    OaUserInfo filemap = oaInfoMapper.findFileInfoByDocID(String.valueOf(sjarry[0]));
//                    String filename = filemap.getImagefilename();
//                    String filepath = filemap.getFilerealpath();
//                    if (StringUtils.isNotBlank(filepath)) {
//                        String zipFilePath = filepath;
//                        String destDirectory = CommonSetData.oaZCFilePath;
//                        String fileName = UnzipUtil.unzip(zipFilePath, destDirectory);
//                        String base64str = "";
//                        try {
//                            String filetype = ".pdf";
//                       /* if (StringUtils.isNotBlank(filename)) {
//                            filetype = filename.substring(filename.lastIndexOf("."));
//                        }*/
//                            // String strname = zipFilePath.substring(zipFilePath.lastIndexOf("\\") + 1, zipFilePath.lastIndexOf("."));
//                            String newFileUrl = destDirectory + File.separator + fileName;
//                            File file = new File(newFileUrl);
//                            base64str = Base64Util.fileToBase64Str(file);
//                            System.out.println(base64str);
//                            file.delete();//删除文件
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                        Map<String, String> fileInfo = new HashMap<String, String>();
//                        fileInfo.put("filename", filename);
//                        fileInfo.put("buffer", base64str);
//
//                        srmLine.put("caccessory", fileInfo);
//                    } else {
//                        srmLine.put("caccessory", "");
//                    }}
                focus_srm_requisitionroutec.add(srmLine);
            }
        }
        armbody.put("focus_srm_requisitionroutec", focus_srm_requisitionroutec);
        JSONObject datatable = new JSONObject();
        datatable.put("user", user);
        datatable.put("voucher", voucher);
        datatable.put("head", head);
        datatable.put("body", armbody);
        String data = JSON.toJSONString(datatable);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        builder.addTextBody("data", data, contentType);
        String s1 = HttpManager.sendPostFormData(srmUrl, builder,data);
        // System.out.println("qingoudan11111:"+builder);
        //String s1 = doPostformdata(srmUrl, data);
        return s1;

    }
}
